package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @GetMapping("/page")
    public Result<PageResult> getByPage(DishPageQueryDTO dishPageQueryDTO){
         return Result.success(dishService.getByPage(dishPageQueryDTO));
    }
    @PostMapping
    public Result<String> save(@RequestBody DishDTO dishDTO){
        dishService.insert(dishDTO);
        Long categoryId=dishDTO.getCategoryId();
        cleanCache("dish_"+categoryId);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        return Result.success(dishService.getById(id));
    }
    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        dishService.update(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }
    @DeleteMapping
    public Result deleteById(@RequestParam List<Long> ids){
        //删除菜品的时候注意如果菜品正在起售中那么不允许删除、如果菜品关联了套餐那么也不允许删除
        dishService.deleteById(ids);
        //直接删除所有缓存数据
        cleanCache("dish_*");
        return Result.success();
    }
    @GetMapping("list")
    public Result<List<Dish>> list(@RequestParam Long categoryId){
        return Result.success(dishService.list(categoryId));
    }
    @PostMapping("status/{status}")
    public Result startOrStop(@PathVariable Integer status,@RequestParam Long id){
        cleanCache("dish_*");
        dishService.startOrStop(status,id);
        return Result.success();
    }
    private void cleanCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
